package com.topcycle.tlight;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.speech.VoiceRecognitionService;
import com.jingchen.timerpicker.TimerPickerView;
import com.mingle.entity.MenuEntity;
import com.mingle.sweetpick.BlurEffect;
import com.mingle.sweetpick.RecyclerViewDelegate;
import com.mingle.sweetpick.SweetSheet;
import com.tosca.colorpicker.ColorPicker;
import com.tosca.colorpicker.ColorPicker.OnWheelChangeListener;
import com.triggertrap.seekarc.SeekArc;
import com.triggertrap.seekarc.SeekArc.OnSeekArcChangeListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends Activity implements RecognitionListener {

	public static final String ACTION_UPDATE_CMD_TEXTVIEW = "update_cmd";
	public static final String ACTION_UPDATE_DEVICE_SPINNER = "update_devices";
	public static final String ACTION_UPDATE_TIMER_TEXTVIEW = "update_timer";
	public static final String ACTION_RENAME_NEW_DEVICE = "rename_new_device";
	public static final String ACTION_NO_NEW_DEVICE = "no_new_device";
	public static final String ACTION_INITIAL_BOX = "initial_box";
	public static final String ACTION_INITIAL_BOX_OK = "initial_box_ok";

	public static final String KEY_NAME_CMD = "key_data_cmd";
	public static final String KEY_TIMER_INDEX = "key_timer_index";
	public static final String KEY_TIMER_IS_LED_ON = "key_timer_is_led_on";
	public static final String KEY_RENAME_DEVICE_MAC = "key_rename_device_mac";
	public static final String KEY_DEVICE_IP = "key_device_ip";
	public static final String BTN_DEVICE_INFO = "btn_device_info";
	public static final String ACTIVITY_RESULT = "activity_result";
	private static final String TAG = "MainActivity";

	private static final int INITIAL_LIGHT_DEGREE = 0;
    private static final int INITIAL_LIGHT_COLOR = 0xffffffff;
	private static final boolean INITIAL_LIGHT_STATE_ON = false;

	private long speechEndTime = -1;
	private static final int EVENT_ERROR = 11;
	private static final int REQUEST_UI = 1;

	private UIUpdateBroadcastReceiver mUIUpdateBroadcastReceiver;
	private TextView mActionBarTitle;
	private TextView mProgressTextView;
	private SweetSheet msweetSheet;
	private SeekArc mSeekBar;
	private ColorPicker mColorPickView;
	private SpeechRecognizer speechRecognizer;
	private View speechTips;
	private View speechWave;
//	private TextView txtResult;
//	private TextView txtLog;
	private List<MenuEntity> mdevNameList;
	private int mCurrentProgress = 100 ;
	private int mCurrentColor = Color.WHITE;
	private DrawerArrowDrawable drawerArrowDrawable;
	private float offset;
	private boolean flipped;
	private boolean lightOn = true;
	private boolean mIsColorWheel = true;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		drawerInit();
		widgetInit();
		colorPickerInit();
		seekBarInit();
		voiceRecognitionInit();
		registerRecevier();
	}

	private void seekBarInit() {
		mProgressTextView = (TextView) findViewById(R.id.percent);
		mSeekBar = (SeekArc) findViewById(R.id.seekbar);
		mSeekBar.setColor(Color.WHITE);
		mSeekBar.setOnSeekArcChangeListener(new SeekBarChangeListener());
	}

	private void drawerInit() {
		ImageButton timerButton = (ImageButton) findViewById(R.id.btn_timer);
		final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		final ImageView imageView = (ImageView) findViewById(R.id.drawer_indicator);
		final Resources resources = getResources();

		drawerArrowDrawable = new DrawerArrowDrawable(resources);
		drawerArrowDrawable.setStrokeColor(resources.getColor(R.color.dark_gray));

		imageView.setImageDrawable(drawerArrowDrawable);

		drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				offset = slideOffset;

				// Sometimes slideOffset ends up so close to but not quite 1 or 0.
				if (slideOffset >= .995) {
					flipped = true;
					drawerArrowDrawable.setFlip(flipped);
				} else if (slideOffset <= .005) {
					flipped = false;
					drawerArrowDrawable.setFlip(flipped);
				}

				drawerArrowDrawable.setParameter(offset);
			}
		});

		imageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (drawer.isDrawerVisible(Gravity.LEFT)) {
					drawer.closeDrawer(Gravity.LEFT);
				} else {
					drawer.openDrawer(Gravity.LEFT);
				}
			}
		});

		mActionBarTitle = (TextView) findViewById(R.id.myactionbar_title);
		if (DeviceManager.getCurrentDevice() != null) {
			mActionBarTitle.setText(DeviceManager.getCurrentDevice().name);
		}

		final ImageView devInfo = (ImageView) findViewById(R.id.dev_info);
		devInfo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if (DeviceManager.getCurrentDevice() == null) {
					return;
				}
				Intent intent = new Intent(MainActivity.this,DevInfoEdit.class);
				Bundle bundle = new Bundle();
				bundle.putInt(BTN_DEVICE_INFO, DeviceManager.getCurrentPos());
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
			}
		});

		ListView listView = (ListView) findViewById(R.id.menu_list);
		ArrayList<HashMap<String,Object>> menuList = new ArrayList<>();
		HashMap<String,Object> menuItem = new HashMap<>();
		menuItem.put("menu_item_img",R.drawable.ic_extension_black_24dp);
		menuItem.put("menu_item_name",getString(R.string.smartconfig));
		menuList.add(menuItem);
		HashMap<String,Object> menuItem1 = new HashMap<>();
		menuItem1.put("menu_item_img",R.drawable.ic_extension_black_24dp);
		menuItem1.put("menu_item_name",getString(R.string.model));
		menuList.add(menuItem1);
		HashMap<String,Object> menuItem2 = new HashMap<>();
		menuItem2.put("menu_item_img",R.drawable.ic_extension_black_24dp);
		menuItem2.put("menu_item_name",getString(R.string.about));
		menuList.add(menuItem2);
		listView.setAdapter(new SimpleAdapter(this, menuList, R.layout.menu_list_item,
				new String[]{"menu_item_img", "menu_item_name"}, new int[]{R.id.menu_item_img, R.id.menu_item_name}));
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				Toast.makeText(getApplicationContext(), position + "clicked", Toast.LENGTH_SHORT).show();
				if (position == 0) {
					Intent intent = new Intent(MainActivity.this,com.espressif.iot.esptouch.demo_activity.EsptouchDemoActivity.class);
					startActivity(intent);
				}
				drawer.closeDrawers();
			}
		});

		timerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				View view = getLayoutInflater().inflate(
						R.layout.timer_picker, null);
				builder.setView(view);
				final TimerPickerView hp = (TimerPickerView) view
						.findViewById(R.id.minute_pv);
				final TimerPickerView mp = (TimerPickerView) view
						.findViewById(R.id.second_pv);;
				final RadioButton openRB = (RadioButton) view
						.findViewById(R.id.open_led_rbtn);
				final Button okBtn = (Button) view
						.findViewById(R.id.timer_ok_btn);
				final Button cancelBtn = (Button) view
						.findViewById(R.id.timer_cancel_btn);
				final AlertDialog dialog = builder.create();
				List<String> data = new ArrayList<String>();
				List<String> minute = new ArrayList<String>();
				for (int i = 0; i < 24; i++)
				{
					data.add(i < 10 ? "0" + i : "" + i);
				}
				for (int i = 0; i < 60; i++) {
					minute.add(i < 10 ? "0" + i : "" + i);
				}
				hp.setData(data);
				mp.setData(minute);
				okBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						NetController.scheduleCmd(openRB.isChecked(),
								hp.getCurrentSelected(), mp.getCurrentSelected()
								);
						System.out.println(hp.getCurrentSelected() + ":" + mp.getCurrentSelected());
						dialog.dismiss();
					}
				});
				cancelBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.show();
			}
		});

	}

	private void voiceRecognitionInit() {
//		txtResult = (TextView) findViewById(R.id.txtResult);
//		txtLog = (TextView) findViewById(R.id.txtLog);


		speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this, new ComponentName(this, VoiceRecognitionService.class));
		speechRecognizer.setRecognitionListener(this);

		speechTips = View.inflate(this, R.layout.bd_asr_popup_speech, null);
		speechWave = speechTips.findViewById(R.id.wave);
		speechTips.setVisibility(View.GONE);
		addContentView(speechTips, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		ImageButton btn_voiceRecognition = (ImageButton) findViewById(R.id.btn_voice);
		btn_voiceRecognition.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						speechTips.setVisibility(View.VISIBLE);
//						speechRecognizer.cancel();
						Intent intent = new Intent();
						bindParams(intent);
						intent.putExtra("vad", "touch");
//						txtResult.setText("");
//						txtLog.setText("");
						speechRecognizer.startListening(intent);
						return true;
					case MotionEvent.ACTION_UP:
						speechRecognizer.stopListening();
						speechTips.setVisibility(View.GONE);
						break;
				}
				return false;
			}
		});
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegisterRecevier();
        DeviceManager.saveToLocal(MainActivity.this);
	}

	private void registerRecevier() {
		mUIUpdateBroadcastReceiver = new UIUpdateBroadcastReceiver();
		IntentFilter uiUpdateFilter = new IntentFilter();
		uiUpdateFilter.addAction(ACTION_UPDATE_CMD_TEXTVIEW);
		uiUpdateFilter.addAction(ACTION_UPDATE_DEVICE_SPINNER);
		uiUpdateFilter.addAction(ACTION_UPDATE_TIMER_TEXTVIEW);
		uiUpdateFilter.addAction(ACTION_RENAME_NEW_DEVICE);
		uiUpdateFilter.addAction(ACTION_NO_NEW_DEVICE);
		uiUpdateFilter.addAction(ACTION_INITIAL_BOX);
		uiUpdateFilter.addAction(ACTION_INITIAL_BOX_OK);

		registerReceiver(mUIUpdateBroadcastReceiver, uiUpdateFilter);
	}

	private void unRegisterRecevier() {
		if (mUIUpdateBroadcastReceiver != null) {
			unregisterReceiver(mUIUpdateBroadcastReceiver);
		}
	}

	private void widgetInit() {
		ImageButton btn_devManager = (ImageButton) findViewById(R.id.show_dev_list);
		btn_devManager.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				msweetSheet.toggle();
				NetController.updateAllDevIp();
			}
		});

		mdevNameList = (DeviceManager.getIndexStringList());
		msweetSheet = new SweetSheet((RelativeLayout)findViewById(R.id.rl));
		msweetSheet.setMenuList(mdevNameList);
		msweetSheet.setDelegate(new RecyclerViewDelegate(true));
		msweetSheet.setBackgroundEffect(new BlurEffect(20));
		msweetSheet.setOnMenuItemClickListener(new SweetSheet.OnMenuItemClickListener() {
			@Override
			public boolean onItemClick(int position, MenuEntity menuEntity) {
				if (position == 0) {
					NetController.findDevice();
					final ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this,"","搜索中");
					new Handler().postDelayed(new Runnable(){
						@Override
						public void run() {
							//// TODO: 16-1-13
							progressDialog.dismiss();
						}
					},1000);
			//		Intent intent = new Intent(MainActivity.this,com.espressif.iot.esptouch.demo_activity.EsptouchDemoActivity.class);
			//		Bundle bundle = new Bundle();
			//		bundle.putInt(BTN_DEVICE_INFO, DeviceManager.getCurrentIndex());
			//		intent.putExtras(bundle);
			//		startActivityForResult(intent, 0);
			//		startActivity(intent);
				}
				if (position > 0) {
					DeviceManager.updateCurrentDeviceByPosition(position-1);
					mActionBarTitle.setText(mdevNameList.get(position).title);
					return true;
				}
				return false;
			}
		});
	}

    @Override
    public void onBackPressed() {

        if(msweetSheet.isShow()){
            msweetSheet.dismiss();
        }
        else{
            super.onBackPressed();
        }
    }

	private void colorPickerInit() {

		mColorPickView = (ColorPicker) findViewById(R.id.color_picker_viewer);
		mColorPickView.setOnWheelChangeListener(new OnWheelChangeListener() {
			@Override
			public void onStartTrackingTouch(ColorPicker colorPicker) {

			}

			@Override
			public void onStopTrackingTouch(ColorPicker colorPicker) {

			}

			@Override
			public void onWheelChange(boolean isColorWheel, int color) {
				mIsColorWheel = isColorWheel;
				if (color == mCurrentColor) {
					return;
				}
				if (isColorWheel) {
					mCurrentColor = color & 0x00FFFFFF;//cw ww closed
				} else {
					mCurrentColor = ((Color.blue(color) & 0xff) << 24);	//rgb closed
				}
				mSeekBar.setColor(color);
				DeviceManager.updateCurrentDeviceState(lightOn,mCurrentProgress,mCurrentColor);
				if (isColorWheel) {
					NetController.sendLightARGBUpdateCmd();
				} else {
					NetController.sendLightDegreeUpdateCmd(mIsColorWheel);
				}
			}

			@Override
			public void onCenterClick(boolean isOn) {
				lightOn = isOn;
				DeviceManager.updateCurrentDeviceState(lightOn,mCurrentProgress,mCurrentColor);
				if(lightOn) {
					NetController.sendLightOnCmd();
				}
				else {
					NetController.sendLightOffCmd();
				}
			}
		});
	}

	private void updateLightState(boolean isOn, int progress, int color) {
	}
	public void bindParams(Intent intent) {
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		if (sp.getBoolean("tips_sound", true)) {
			intent.putExtra(Constant.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
			intent.putExtra(Constant.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
			intent.putExtra(Constant.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
			intent.putExtra(Constant.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
			intent.putExtra(Constant.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
		}
		if (sp.contains(Constant.EXTRA_INFILE)) {
			String tmp = sp.getString(Constant.EXTRA_INFILE, "").replaceAll(",.*", "").trim();
			intent.putExtra(Constant.EXTRA_INFILE, tmp);
		}
		if (sp.getBoolean(Constant.EXTRA_OUTFILE, false)) {
			intent.putExtra(Constant.EXTRA_OUTFILE, "sdcard/outfile.pcm");
		}
		if (sp.contains(Constant.EXTRA_SAMPLE)) {
			String tmp = sp.getString(Constant.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim();
			if (null != tmp && !"".equals(tmp)) {
				intent.putExtra(Constant.EXTRA_SAMPLE, Integer.parseInt(tmp));
			}
		}
		if (sp.contains(Constant.EXTRA_LANGUAGE)) {
			String tmp = sp.getString(Constant.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim();
			if (null != tmp && !"".equals(tmp)) {
				intent.putExtra(Constant.EXTRA_LANGUAGE, tmp);
			}
		}
		if (sp.contains(Constant.EXTRA_NLU)) {
			String tmp = sp.getString(Constant.EXTRA_NLU, "").replaceAll(",.*", "").trim();
			if (null != tmp && !"".equals(tmp)) {
				intent.putExtra(Constant.EXTRA_NLU, tmp);
			}
		}

		if (sp.contains(Constant.EXTRA_VAD)) {
			String tmp = sp.getString(Constant.EXTRA_VAD, "").replaceAll(",.*", "").trim();
			if (null != tmp && !"".equals(tmp)) {
				intent.putExtra(Constant.EXTRA_VAD, tmp);
			}
		}
		String prop = null;
		if (sp.contains(Constant.EXTRA_PROP)) {
			String tmp = sp.getString(Constant.EXTRA_PROP, "").replaceAll(",.*", "").trim();
			if (null != tmp && !"".equals(tmp)) {
				intent.putExtra(Constant.EXTRA_PROP, Integer.parseInt(tmp));
				prop = tmp;
			}
		}
		// offline asr
		{
			intent.putExtra(Constant.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1");

			if (null != prop) {
				int propInt = Integer.parseInt(prop);
				if (propInt == 10060) {
					intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_Navi");
				} else if (propInt == 20000) {
					intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_InputMethod");
				}
			}
			intent.putExtra(Constant.EXTRA_OFFLINE_SLOT_DATA, buildTestSlotData());
		}
	}
	private String buildTestSlotData() {
		JSONObject slotData = new JSONObject();
		JSONArray usercommand = new JSONArray().put("关灯").put("开门");
		return slotData.toString();
	}

	@Override
	public void onReadyForSpeech(Bundle params) {

	}

	@Override
	public void onBeginningOfSpeech() {

	}

	@Override
	public void onRmsChanged(float rmsdB) {
		final int VTAG = 0xFF00AA01;
		Integer rawHeight = (Integer) speechWave.getTag(VTAG);
		if (rawHeight == null) {
			rawHeight = speechWave.getLayoutParams().height;
			speechWave.setTag(VTAG, rawHeight);
		}

		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) speechWave.getLayoutParams();
		params.height = (int) (rawHeight * rmsdB * 0.01);
		params.height = Math.max(params.height , speechWave.getMeasuredWidth());
		speechWave.setLayoutParams(params);
	}

	@Override
	public void onBufferReceived(byte[] buffer) {

	}

	@Override
	public void onEndOfSpeech() {

	}

	@Override
	public void onError(int error) {
		StringBuilder sb = new StringBuilder();
		switch (error) {
			case SpeechRecognizer.ERROR_AUDIO:
				sb.append("音频问题");
				break;
			case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
				sb.append("没有语音输入");
				break;
			case SpeechRecognizer.ERROR_CLIENT:
				sb.append("其它客户端错误");
				break;
			case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
				sb.append("权限不足");
				break;
			case SpeechRecognizer.ERROR_NETWORK:
				sb.append("网络问题");
				break;
			case SpeechRecognizer.ERROR_NO_MATCH:
				sb.append("没有匹配的识别结果");
				break;
			case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
				sb.append("引擎忙");
				break;
			case SpeechRecognizer.ERROR_SERVER:
				sb.append("服务端错误");
				break;
			case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
				sb.append("连接超时");
				break;
		}
		sb.append(":" + error);
		print("识别失败：" + sb.toString());
	}

	@Override
	public void onResults(Bundle results) {
//		long end2finish = System.currentTimeMillis() - speechEndTime;
		ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//		print("识别成功：" + Arrays.toString(nbest.toArray(new String[nbest.size()])));
//		String json_res = results.getString("origin_result");
//		try {
//			print("origin_result=\n" + new JSONObject(json_res).toString(4));
//		} catch (Exception e) {
//			print("origin_result=[warning: bad json]\n" + json_res);
//		}
//		String strEnd2Finish = "";
//		if (end2finish < 60 * 1000) {
//			strEnd2Finish = "(waited " + end2finish + "ms)";
//		}

//		txtResult.setText(nbest.get(0));
		dealVoiceCommand(nbest.get(0));
	}

	private void dealVoiceCommand (String s) {
		for (int i = 0; i<10;i++) {
			s = s.replace(Voice.NUM_HAN[i], Voice.NUM[i]);
		}
		Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
		for (int i=0;i<mdevNameList.size();i++) {
			if (s.contains(mdevNameList.get(i).title)) {
				System.out.println("dev"+i);
				Toast.makeText(MainActivity.this, mdevNameList.get(i).title, Toast.LENGTH_SHORT).show();
				DeviceManager.updateCurrentDeviceByPosition(i);
				break;
			}
		}
		if (s.contains(Voice.LIGHTON)) {
			NetController.sendLightOnCmd();
		}
		else if (s.contains(Voice.LIGHTOFF)) {
			NetController.sendLightOffCmd();
		}
		if (s.contains(Voice.COLOR_BLUE)) {
			mCurrentColor = Voice.color_blue;
			DeviceManager.updateCurrentDeviceState(true, mCurrentProgress, mCurrentColor);
//			mcolorPicker.setColor(mCurrentColor);
		}
		else if (s.contains(Voice.COLOR_RED)) {
			mCurrentColor = Voice.color_red;
			DeviceManager.updateCurrentDeviceState(true, mCurrentProgress, mCurrentColor);
//			mcolorPicker.setColor(mCurrentColor);
		}
		else if (s.contains(Voice.COLOR_GREEN)) {
			mCurrentColor = Voice.color_green;
			DeviceManager.updateCurrentDeviceState(true, mCurrentProgress, mCurrentColor);
//			mcolorPicker.setColor(mCurrentColor);
		}
	}

	@Override
	public void onPartialResults(Bundle partialResults) {
//		ArrayList<String> nbest = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//		if (nbest.size() > 0) {
//			print("~临时识别结果：" + Arrays.toString(nbest.toArray(new String[0])));
//			txtResult.setText(nbest.get(0));
//		}
	}

	@Override
	public void onEvent(int eventType, Bundle params) {
//		switch (eventType) {
//			case EVENT_ERROR:
//				String reason = params.get("reason") + "";
//				print("EVENT_ERROR, " + reason);
//				break;
//		}
	}

	private void print(String msg) {
//		txtLog.append(msg + "\n");
//		ScrollView sv = (ScrollView) txtLog.getParent();
//		sv.smoothScrollTo(0, 1000000);
		Log.d(TAG, "----" + msg);
	}

	class SeekBarChangeListener implements OnSeekArcChangeListener {

		@Override
		public void onStopTrackingTouch(SeekArc seekArc) {
		}

		@Override
		public void onStartTrackingTouch(SeekArc seekArc) {
		}

		@Override
		public void onProgressChanged(SeekArc seekArc, int progress,
									  boolean fromUser) {
			System.out.println("newProgress:" + progress + ", fromUser: "
					+ fromUser);
			if (fromUser) {
				if (progress == mCurrentProgress) {
					return;
				}
				mCurrentProgress = progress;
				mProgressTextView.setText(progress + "%");
				DeviceManager.updateCurrentDeviceState(
						true, progress, mCurrentColor);
				NetController.sendLightDegreeUpdateCmd(mIsColorWheel);
			}
		}
	}

	class UIUpdateBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_UPDATE_CMD_TEXTVIEW.equals(action)) {
				byte cmd[] = intent.getByteArrayExtra(KEY_NAME_CMD);

			} else if (ACTION_UPDATE_DEVICE_SPINNER.equals(action)) {
				if (DeviceManager.getCurrentDevice() != null) {

				}
				updateDevList();
			} else if (ACTION_UPDATE_TIMER_TEXTVIEW.equals(action)) {
				Device device = DeviceManager.getCurrentDevice();
				updateLightState(device.isOn, device.light, device.color);
			} else if (ACTION_RENAME_NEW_DEVICE.equals(action)) {

				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				final byte[] mac_data = intent.getByteArrayExtra(KEY_RENAME_DEVICE_MAC);
				final byte[] ip_data = intent.getByteArrayExtra(KEY_DEVICE_IP);

				builder.setTitle("Create Name for Device " + Utils.bytesToHexString(mac_data,3,3));
				View view = (LinearLayout) getLayoutInflater().inflate(
						R.layout.device_rename_dialog, null);
				builder.setView(view);
				final EditText et = (EditText) view
						.findViewById(R.id.rename_et);
				builder.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								DeviceManager.renameDevice(mac_data, ip_data, et.getText().toString());
								updateDevList();
								dialog.dismiss();
							}
						});
				builder.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		}
	}

	private void updateDevList() {
		mdevNameList.clear();
		mdevNameList.addAll(DeviceManager.getIndexStringList());
		msweetSheet.setMenuList(mdevNameList);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			String result = data.getExtras().getString(ACTIVITY_RESULT);
			System.out.println(result);
			updateDevList();

			if (DeviceManager.getCurrentDevice() == null) {
				mActionBarTitle.setText("T-light");
			} else {
				mActionBarTitle.setText(DeviceManager.getCurrentDevice().name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		DeviceManager.saveToLocal(MainActivity.this);
	}
}
